use std::{env, process};
extern crate paho_mqtt as mqtt;
const DFLT_BROKER: &str = "mqtt://broker.emqx.io:1883";

const QOS: i32 = 1;
fn main() {
    // env_logger::init();
    let host = env::args()
        .nth(1)
        .unwrap_or_else(|| DFLT_BROKER.to_string());

    let cli = mqtt::AsyncClient::new(host).unwrap_or_else(|err| {
        println!("Error creating the client: {}", err);
        process::exit(1);
    });

    let conn_opts = mqtt::ConnectOptions::new();

    if let Err(e) = cli.connect(conn_opts).wait() {
        println!("unable to connect:{:?}", e);
        process::exit(1);
    }

    println!("Publishing messages on the 'test' topic");
    let topic = mqtt::Topic::new(&cli, "test/rust/mq", QOS);
    for _ in 0..5 {
        let tok = topic.publish("Hello there");
        if let Err(e) = tok.wait() {
            println!("Error sending message :{:?}", e);
            break;
        }
    }

    //Disconnect from the broker
    let tok = cli.disconnect(None);
    tok.wait().unwrap();
}
